<?php

namespace App\Http\Controllers;

use Alipay\OpenAPISDK\Api\AlipayTradeApi;
use Alipay\OpenAPISDK\ApiException;
use Alipay\OpenAPISDK\Model\AlipayTradePayModel;
use Alipay\OpenAPISDK\Model\AlipayTradeQueryModel;
use App\Models\Lz\Depositrecord;
use GuzzleHttp\Client;
use Alipay\OpenAPISDK\Util\Model\AlipayConfig;

use Alipay\OpenAPISDK\Util\AlipayConfigUtil;
use Alipay\OpenAPISDK\Util\GenericExecuteApi;

use Alipay\OpenAPISDK\Util\Model\CustomizedParams;
use Alipay\OpenAPISDK\Util\Model\OpenApiGenericRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;


class PayController extends Controller
{
    private $appid = null;
    protected $privateKey = null;
    protected $publicKey = null;

//    private $appid = '2021004170645344';
//    protected $privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwA6+7LuBROUMF1MK10mrv8H1xK/9zB6PUjF+3mvaTCE4+OLZSIU72UuGoXkeZIQE9VEwqPFqTAsvWBuBOGim26frlBJxh0zUX+hwyFGxPiM55jvI+YCWo3wEfOT9QUk8Lw3U0H8C/VLl6xd7hbLb0ajbjDfPQEP86yCigngZfI+E0WpOGiVcl1Qp+vXqzWJi0iGFI2W7dBLbik+mRE1wKOjwU3KD1EdyWbLz8Eu69q4/5ReiYKi+nZTPWRSdxqwdsY1EoJECaj2M38O7iaKGhpf9SkeT7A+6n61C8DfBOZSV2ipkVp6azAAu6+SkJIFsDxuRzi1YZ3HZpq7nVlhdBAgMBAAECggEALfaoez8AgPVtFSa8OfLazhGFEHqm2IkUNTr6+91Rqo+urvzsT4I3NofqOad1Fv3RbwyGXzknheBjDl75UCvw3L05MXkExV78LGi52DIRHqvhD0lO5Q8ChpjFmDvA1t7HmZDPGG96S/x5+x+U1lUnaaga8SwBkUH/BICka10Y2Nr8yDAjfkItRiw0PPcBRwOOKkNXLtDXrqVFjMgb0vpna3DovyVkfW4FaADoA4M63KpPv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j3He45vm8hrxBqJaLJos+UWRhWJjvF3hT/F3X9sUhppexjlArFYRiJ06UTdiPMU66tj6I8GXIH7udgkVix2upoVRODFnGeTsvKb6K28wErBrWv2nTZ2a8FGbC7cgD89VmHjSl/6WM8gA3OihLjxl0jFME9RQJ016/DSA+S0GIjbC/KdIzi1yHAvWAt56+gPROLi/YQxXqXafwFf96e/w99w6rrkE/Osiw3NHxImTa1lLLg+GQr2oLKhw08USKdMdJLqxvJzDZ8KPwtv4ayn5IjQ1+7AWvzHMegz2oiSr0WYy9Q4KLxMC+KHQIDAQAB';


    public function __construct()
    {
        $config = config('alipay.pc_pay');
        $this->appid = $config['appid'];
        $this->privateKey = $config['app_private_key'];
        $this->publicKey = $config['public_key'];

//        $this->appid = '2021004170645344';
//        $this->privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwA6+7LuBROUMF1MK10mrv8H1xK/9zB6PUjF+3mvaTCE4+OLZSIU72UuGoXkeZIQE9VEwqPFqTAsvWBuBOGim26frlBJxh0zUX+hwyFGxPiM55jvI+YCWo3wEfOT9QUk8Lw3U0H8C/VLl6xd7hbLb0ajbjDfPQEP86yCigngZfI+E0WpOGiVcl1Qp+vXqzWJi0iGFI2W7dBLbik+mRE1wKOjwU3KD1EdyWbLz8Eu69q4/5ReiYKi+nZTPWRSdxqwdsY1EoJECaj2M38O7iaKGhpf9SkeT7A+6n61C8DfBOZSV2ipkVp6azAAu6+SkJIFsDxuRzi1YZ3HZpq7nVlhdBAgMBAAECggEALfaoez8AgPVtFSa8OfLazhGFEHqm2IkUNTr6+91Rqo+urvzsT4I3NofqOad1Fv3RbwyGXzknheBjDl75UCvw3L05MXkExV78LGi52DIRHqvhD0lO5Q8ChpjFmDvA1t7HmZDPGG96S/x5+x+U1lUnaaga8SwBkUH/BICka10Y2Nr8yDAjfkItRiw0PPcBRwOOKkNXLtDXrqVFjMgb0vpna3DovyVkfW4FaADoA4M63KpPvxF+BfYDrN9Bm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BqJaLJos+UWRhWJjvF3hT/F3X9sUhppexjlArFYRiJ06UTdiPMU66tj6I8GXIH7udgkVix2upoVRODFnGeTsvKb6K28wErBrWv2nTZ2a8FGbC7cgD89VmHjSl/6WM8gA3OihLjxl0jFME9RQJ016/DSA+S0GIjbC/KdIzi1yHAvWAt56+gPROLi/YQxXqXafwFf96e/w99w6rrkE/Osiw3NHxImTa1lLLg+GQr2oLKhw08USKdMdJLqxvJzDZ8KPwtv4ayn5IjQ1+7AWvzHMegz2oiSr0WYy9Q4KLxMC+KHQIDAQAB';


    }

    protected function jwt($token)
    {
        list(, $b,) = explode('.', $token);
        $payload = $this->base64_decodeUrl($b);
        return json_decode($payload, true);
    }

    protected function test(Request $request)
    {
        $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjM1MTlmY2JkLWNjYmEtNGY1OS1iNzhjLWI4ZTJlY2JhMjNlYiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJhZG1pbiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6ImFkbWluIiwibmJmIjoxNzI1ODg5ODA1LCJleHAiOjE3MzEwNzM4MDUsImlzcyI6IkJhY2tlbmQiLCJhdWQiOiJCYWNrZW5kIn0.mUTCZRgQqGLeMV5mBvcEZ9i5L9NsAvqAoXfC0OGNr7U';
        $this->getConfig($token);
    }

    protected function getConfig($token)
    {
        $result = Http::withToken($token)->get('http://backend.lanzhankeji.com/api/AppBackend/Pay/getPrice')->json();
        if (empty($result)) {
            return false;
        }
        return $result;
    }


    public function base64_decodeUrl($input)
    {
        // 将URL安全的Base64字符串转换为标准Base64字符串
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    public function pc(Request $request)
    {
        $params = $request->all();
        $token = $params['token'];
        $type = $params['type'] ?: 0;

        $count = $params['count'];
        if (empty($count)) {
            return response()->json([
                'isError'        => true,
                'errorMessage'   => '请输入充值数量',
                'successMessage' => null,
            ]);
        }
        $number = $count % 100;
        if ($number !== 0) {
            return response()->json([
                'isError'        => true,
                'errorMessage'   => '充值数量必须是100的倍数',
                'successMessage' => null,
            ]);
        }
        $userData = $this->jwt($token);
        $userId = $userData['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'];
        $userName = $userData['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'];
        $goodsName = '渠道商进件充值';
        $outTradeNo = build_uri();
        $config = $this->getConfig($token);
        if (empty($config)) {
            return response()->json([
                'isError'        => true,
                'errorMessage'   => '获取配置信息错误',
                'successMessage' => null,
            ]);
        }
        if ($type == 0) {
            $price = $config['inPrice'];
            if (empty($price)) {
                return response()->json([
                    'isError'        => true,
                    'errorMessage'   => '当前未设置进件价格',
                    'successMessage' => null,
                ]);
            }
            $strPrice = $config['inPriceStr'];
        } elseif ($type == 1) {
            $price = $config['smsPrice'];
            if (empty($price)) {
                return response()->json([
                    'isError'        => true,
                    'errorMessage'   => '当前未设置短信价格',
                    'successMessage' => null,
                ]);
            }
            $strPrice = $config['smsPriceStr'];
            return response()->json([
                'isError'        => true,
                'errorMessage'   => '暂不支持短信充值',
                'successMessage' => null,
            ]);
        } else {
            return response()->json([
                'isError'        => true,
                'errorMessage'   => '未知充值类型',
                'successMessage' => null,
            ]);
        }
        $num = $count / 100;
        $amount = bcmul($strPrice, strval($num), 2);
        Depositrecord::query()->insert([
            'ID'                  => $outTradeNo,
            'IsAble'              => 1,
            'Amout'               => $amount,
            'Count'               => $count,
            'PayUserId'           => $userId,
            'PayUserName'         => $userName,
            'Note'                => $goodsName,
            'CreateTime'          => date('Y-m-d H:i:s'),
            'DepositRecordStatus' => 0,
            'PayMethod'           => 0,
            'Type'                => $type,
            'PayTime'             => '0001-01-01 00:00:00',
            'OutOrderID'          => $outTradeNo,
        ]);
        // 初始化SDK
        $alipayConfigUtil = new AlipayConfigUtil($this->getAlipayConfig());

        $apiInstance = new GenericExecuteApi(
            $alipayConfigUtil,
            new Client()
        );
        // 构造请求参数以调用接口
        $bizParams = array();
        $bizContent = array();
        // 设置订单绝对超时时间
        $bizContent['time_expire'] = date('Y-m-d H:i:s', time() + 30 * 60);// 设置订单标题
        $bizContent['subject'] = $goodsName;
        // 设置产品码
        $bizContent['product_code'] = "FAST_INSTANT_TRADE_PAY";
        // 设置订单附加信息
        $bizContent['body'] = "充值进件量" . $count . '个';
        // 设置PC扫码支付的方式
        //        $bizContent['qr_pay_mode'] = "1";// 设置请求后页面的集成方式
        $bizContent['integration_type'] = "PCWEB";

        // 设置请求来源地址
        $bizContent['request_from_url'] = "https://";

        // 设置商户自定义二维码宽度
        $bizContent['qrcode_width'] = 100;
//        $bizContent['notify_url'] = 'https://api.lanzhankeji.com/api/notify/pay';
//        $bizContent['return_url'] = 'http://admin.lanzhankeji.com';


        // 设置商户订单号
        $bizContent['out_trade_no'] = $outTradeNo;
        if ($userId == "ec36fc29-d664-4e69-a3e1-7371938470a0") {
            $amount = 0.01;
        }
//        $amount = 0.01;
        // 设置订单总金额
        $bizContent['total_amount'] = bcadd($amount, 0, 2);


        $bizParams['biz_content'] = $bizContent;
        $bizParams['notify_url'] = 'https://api.lanzhankeji.com/api/notify/pay';
        $bizParams['return_url'] = 'http://admin.lanzhankeji.com/pay/moneyrecord';

        try {
            // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
            //$pageRedirectionData = $apiInstance->pageExecute('alipay.trade.page.pay', 'POST', $bizParams);

            // 如果需要返回GET请求，请使用
            $pageRedirectionData = $apiInstance->pageExecute('alipay.trade.page.pay', 'GET', $bizParams);
            Depositrecord::query()->where('ID', $outTradeNo)->update([
                'OrderStatus' => 1,//待支付
                'QrLink'      => $pageRedirectionData,
            ]);
            return response()->json([
                'url' => $pageRedirectionData,
            ]);
        } catch (ApiException $e) {
            Depositrecord::query()->where('ID', $outTradeNo)->update([
                'Message'     => $e->getMessage(),
                'TradeStatus' => 'TradeFail',
                'OrderStatus' => 5,//失败
            ]);
        }

        return response()->json([
            'url' => 'http://admin.lanzhankeji.com',
        ]);
    }

    public function getAlipayConfig()
    {
        $alipayConfig = new AlipayConfig();
        $alipayConfig->setServerUrl('https://openapi.alipay.com');
        $alipayConfig->setAppId($this->appid);
        $alipayConfig->setPrivateKey($this->privateKey);
        $alipayConfig->setAlipayPublicKey($this->publicKey);
        return $alipayConfig;
    }

    public function query()
    {
        // 初始化SDK
        $alipayConfigUtil = new AlipayConfigUtil($this->getAlipayConfig());

// 构造请求参数以调用接口
        $apiInstance = new AlipayTradeApi(
            new Client()
        );
// 设置AlipayConfigUtil
        $apiInstance->setAlipayConfigUtil($alipayConfigUtil);
        $data = new AlipayTradeQueryModel();

// 设置订单支付时传入的商户订单号
        $data->setOutTradeNo("240907oybb5du4aoekamjt");

        try {
            $result = $apiInstance->query($data);
            print_r($result);
        } catch (ApiException $e) {
            echo '调用失败: ', $e->getMessage(), PHP_EOL;
            echo 'body: ', $e->getResponseBody(), PHP_EOL;
            var_dump('header: ', $e->getResponseHeaders());
        }

    }
}
